package cn.vawn.medical.service.impl;

import cn.vawn.medical.constant.MedicalCard;
import cn.vawn.medical.entity.NormalUser;
import cn.vawn.medical.entity.TeamUser;
import cn.vawn.medical.mapper.NormalUserMapper;
import cn.vawn.medical.mapper.SmsMapper;
import cn.vawn.medical.mapper.TeamUserMapper;
import cn.vawn.medical.service.INormalUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service("normalUserService")
public class NormalUserServiceImpl implements INormalUserService {

	@Resource
	private NormalUserMapper normalUserMapper;
	
	@Resource
	private TeamUserMapper teamUserMapper;
	
	@Resource
	private SmsMapper smsMapper;
	
	/*******
	 * ���һ����ͨ�û�
	 */
	public void insertNormalUser(NormalUser user) {
		normalUserMapper.insertSelective(user);
	}

	
	/*****
	 * �������֤�����½
	 * 
	 * ����ҵ���д���ȶ
	 */
	public boolean checkUserLoginByIdCard(String idCard, String password) {
		//��������ͨ�û����в��Ҹ��û�
		NormalUser normalUser = normalUserMapper.selectUserByIdCard(idCard);
		
		//���û�����ͨ�û����д���
		if (normalUser != null){
			//�ж������Ƿ�ƥ��
			if (normalUser.getPassword() != null &&
					normalUser.getPassword().equals(password)){
				return true;
			} else {
				return false;
			}
		}
		
		//Ȼ���������û����в����û�
		TeamUser teamUser = teamUserMapper.selectUserByIdCard(idCard);
		//���û����������
		if (teamUser != null){
			//�ж������Ƕ�ƥ��
			if (teamUser.getPassword() != null && 
					teamUser.getPassword().equals(password)){
				return true;
			} else {
				return false;
			}
		}
		
		//�������������֤�˺������Ƿ�ƥ��(Ԥ��)
		
		return false;
	}

	/*****
	 * �����ֻ��ź���֤���½
	 */
	public int checkUserLoginByMobile(String mobile, String code) {
		//�����ֻ��Ų�ѯ��֤��
		String checkCode = smsMapper.checkCodeByMobile(mobile);
		
		//�ֻ��Ų�����
		if (checkCode == null){
			return MedicalCard.NOT_FIND_CODE;
		} else {
			//��֤�벻ƥ��
			if (!checkCode.equals(code)){
				return MedicalCard.CHECK_CODE_FALSE;
			} else {
				//��֤��ƥ��ɹ�
				return MedicalCard.CHECK_CODE_SUCCESS;
			}
		}
	}

	/********
	 * �����ֻ����޸�����
	 */
	public boolean updatePasswordByMobile(String mobile, String password, String code) {
		//������֤�������֤���Ƿ�ƥ��
		String select_code = smsMapper.checkCodeByMobile(mobile);
		
		//��֤�벻ƥ��
		if (!(select_code != null && select_code.equals(code))) {
			return false;
		}
		//��֤��ƥ��,�����޸�����
		normalUserMapper.updatePassword(mobile, password);
		
		return true;
	}

	@Override
	public NormalUser getNormalUserByCondition(Map<String, Object> map) {
		return normalUserMapper.selectNormalUserByCondition(map);
	}

	@Transactional(rollbackFor = {Exception.class})
	@Override
	public void updateNormalUser(NormalUser dbNormalUser) {
		normalUserMapper.updateByPrimaryKey(dbNormalUser);
	}

}
